package com.authine.cloudpivot.controller;

import cn.hutool.core.bean.BeanUtil;
import com.authine.cloudpivot.domain.Dto.CorpConfigDto;
import com.authine.cloudpivot.foundation.orm.api.dml.JPANativeQuery;
import com.authine.cloudpivot.util.DingDingUtil;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/DingUser")
@Slf4j
public class DingUserController extends BaseController {
    @Autowired
    private JPANativeQuery jpaNativeQuery;

    public CorpConfigDto getAppConfigByCorPid(String corpId){
        String sql = String.format("SELECT agentId,appkey as appKey,appSecret FROM `h_related_corp_setting`   where corpId ='%s' ",corpId);
        List<Map<String,Object>> list =jpaNativeQuery.getList(sql, null, null);
        Map<String, Object> objectMap = list.get(0);
        CorpConfigDto corpConfigDto = BeanUtil.mapToBean(objectMap, CorpConfigDto.class, true);
        return corpConfigDto;
    }

    /**
     * 清理僵尸用户
     */
    @GetMapping("/clear")
    public void clearZombieUser(){
//        String sql = "SELECT \n" +
//                "jd.name AS '街道',\n" +
//                "sq.name AS '社区',\n" +
//                "wbj.name AS '委办局',\n" +
//                "u.name AS '人员',\n" +
//                "u.mobile AS '电话',\n" +
//                "u.userId,\n" +
//                "u.corpId\n" +
//                "FROM ikhmj_txl t\n" +
//                "LEFT JOIN h_org_user u ON t.ry=u.id\n" +
//                "LEFT JOIN h_org_department jd ON t.jd=jd.id\n" +
//                "LEFT JOIN h_org_department sq ON t.sq=sq.id\n" +
//                "LEFT JOIN h_org_department wbj ON t.wbdw = wbj.id\n" +
//                "WHERE t.ry NOT IN\n" +
//                "(\n" +
//                "SELECT DISTINCT userid FROM h_log_login WHERE loginTime BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND CURDATE()\n" +
//                ")\n" +
//                "order by u.corpId";
        String sql = "SELECT\n" +
                "\tjd.NAME AS '街道',\n" +
                "\tsq.NAME AS '社区',\n" +
                "\twbj.NAME AS '委办局',\n" +
                "\tu.NAME AS '人员',\n" +
                "\tu.mobile AS '电话',\n" +
                "\tu.userId,\n" +
                "\tu.corpId \n" +
                "FROM\n" +
                "\tikhmj_txl t\n" +
                "\tLEFT JOIN h_org_user u ON t.ry = u.id\n" +
                "\tLEFT JOIN h_org_department jd ON t.jd = jd.id\n" +
                "\tLEFT JOIN h_org_department sq ON t.sq = sq.id\n" +
                "\tLEFT JOIN h_org_department wbj ON t.wbdw = wbj.id \n" +
                "\n" +
                "ORDER BY\n" +
                "\tu.corpId";
        List<Map<String,Object>> list = jpaNativeQuery.getList(sql, null, null);
        if (CollectionUtils.isNotEmpty(list)){
            Map<String, List<String>> groupedByCorpId = list.stream()
                    .collect(Collectors.groupingBy(
                            m -> String.valueOf(m.get("corpId")),
                            Collectors.mapping(
                                    m -> String.valueOf(m.get("userId")),
                                    Collectors.toList()
                            )
                    ));
            groupedByCorpId.forEach((corpId, userIds) -> {
                CorpConfigDto corpConfigDto = getAppConfigByCorPid(corpId);
                if (Objects.nonNull(corpConfigDto)){
                    try {
                        DingDingUtil.Appscopes(corpConfigDto.getAppKey(),corpConfigDto.getAppSecret(),corpConfigDto.getAgentId(),userIds);
                    } catch (Exception e) {
                        log.error("修改应用权限失败");
                        throw new RuntimeException(e.getMessage(),e);
                    }
                }
            });

        }

    }

    @GetMapping("/addAuth")
    public void addAuth(){

    }
}
